# -*- coding: utf-8 -*-
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from myplugins.models import MyText as MyTextModel, ProductRandom as PR, YaPg, d3News
from django.utils.translation import ugettext as _
from catalog.models import *
import random
from django.http import HttpResponse

import urllib
import lxml.html as html

class MyTextPlugin(CMSPluginBase):
    model = MyTextModel # Model where data about this plugin is saved
    name = _(u"Текст на страницах") # Name of the plugin
    render_template = "content.html" # template to render the plugin with

    def render(self, context, instance, placeholder):
        context.update({'instance':instance})
        return context

plugin_pool.register_plugin(MyTextPlugin) # register the plugin

class ProductRandom(CMSPluginBase):
    model = PR
    name = _(u'Случайные товары с картинками')
    render_template = "product-random.html"
    
    def render(self, context, instance, placeholder):
        product = list(Product.objects.all())
        random.shuffle(product)
        context.update({'product': product[:instance.kol]})
        return context

plugin_pool.register_plugin(ProductRandom)  

class YPPlugin(CMSPluginBase):
    model = YaPg
    name = _(u'Погода Яндекс')
    render_template = "ya_pg.html"
    
    def render(self, context, instance, placeholder):
        return context

plugin_pool.register_plugin(YPPlugin)   

class d3NewsPlugin(CMSPluginBase):
    model = d3News
    name = _(u'Новости с 3DNews.ru')
    render_template = "3dnews.html"
    
    def render(self, context, instance, placeholder):
        page = urllib.urlopen('http://www.3dnews.ru/news/')
#        page = urllib.urlopen('http://www.3dnews.ru/software-news/')
        doc = html.document_fromstring(page.read())
        divNews = [html.tostring(news).replace('/_imgdata', 'http://3dnews.ru/_imgdata').replace('a href="/', 'a href="http://3dnews.ru/') for news in doc.cssselect('.newsArticle')]
        context.update({'news': divNews[1:]})
        return context

plugin_pool.register_plugin(d3NewsPlugin) 